package uk.ac.aber.paws.server.remoteinstall;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import java.util.logging.Level;

import uk.ac.aber.paws.server.config.ConfigManager;
import uk.ac.aber.paws.server.config.Constants;
import uk.ac.aber.paws.server.core.PAWSInstaller;
import uk.ac.aber.paws.server.util.FileOperations;

/**
 * @author Rob Johnson, Aberystwyth University
 * @email rob.johnson@aber.ac.uk
 * @date 21st May 2012
 * 
 * PAWSClientInstall.java
 * 
 * This class deals with the tasks to perform remote installation tasks on the PAWS client computers
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class PAWSClientInstall extends RemoteInstallOperations {

	Hashtable<String,Object> requestData;
	
	public static final int PAWSINSTALLTYPE_FULLINSTALL = 0;
    public static final int PAWSINSTALLTYPE_UPDATEPAWS = 1;
    public static final int PAWSINSTALLTYPE_UPDATEPAWSCONFIG = 2;
    public static final int PAWSINSTALLTYPE_UPDATEPAWSMANAGER = 3;
    public static final int PAWSINSTALLTYPE_UPDATEPAWSLIBS = 4;
        
    private int installOption;
    
	public PAWSClientInstall(Hashtable<String,Object> requestData, int installOption) {
		
		this.requestData = requestData;
		this.installOption = installOption;
		
		this.start();
		
	}
	
	public void run() {
		
		// a full PAWS installation
		if (this.installOption == PAWSINSTALLTYPE_FULLINSTALL) {
			fullInstall();
		}
		// a PAWS update
		else if (this.installOption == PAWSINSTALLTYPE_UPDATEPAWS) {
			pawsClientUpgrade();
		}
		// a PAWS Client Manager update
		else if (this.installOption == PAWSINSTALLTYPE_UPDATEPAWSMANAGER) {
			updatePAWSManager();
		}
		// a PAWS config update
		else if (this.installOption == PAWSINSTALLTYPE_UPDATEPAWSCONFIG) {
			updatePAWSConfig();
		}
		// a PAWS library update
		else if (this.installOption == PAWSINSTALLTYPE_UPDATEPAWSLIBS) {
			updatePAWSLibs();
		}
	}
	
	/**
	 * Called to perform the relevant commands to update the PAWS Client Manager
	 */
	private void updatePAWSManager() {
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_INPROGRESS);
			
		String destFile = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsclientmanager");
		
		String sourceFile = ConfigManager.getProperty("app.remoteinstall.source.pawsclientmanager");
		
		copyFileToClient(sourceFile,destFile);
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_COMPLETED);
		
	}
	
	/**
	 * Called to perform the PAWS configuration update on the client
	 */
	private void updatePAWSConfig() {
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_INPROGRESS);
			
		String destFolder = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsconfigfolder");
		
		FileOperations.mirrorDirectories(new File(ConfigManager.getProperty("app.remoteinstall.source.pawsconfigfolder")),new File(destFolder));
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_COMPLETED);
		
	}

	/**
	 * Called to perform the PAWS 3rd party library updates on the client
	 */
	private void updatePAWSLibs() {
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_INPROGRESS);
			
		String destFolder = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawslibfolder");
		
		FileOperations.mirrorDirectories(new File(ConfigManager.getProperty("app.remoteinstall.source.pawslibfolder")),new File(destFolder));
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_COMPLETED);
		
	}

	/**
	 * Called to perform a PAWS Client update on the client computer
	 */
	private void pawsClientUpgrade() {
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_INPROGRESS);
		
		// stop the PAWS Client service
		togglePAWSService(false,(String)requestData.get("FQDN"));
	
		boolean cleanIt = false;
		
		if (requestData.get("CleanDestFolder") != null) {
			if ((Integer)requestData.get("CleanDestFolder") == 1) {
				cleanIt = true;
				
				// perform a full upgrade if option to clean up is selected
				copyPAWSFolderToClient(cleanIt);
			}
		}
		
		// if clean not required, just copy existing files
		if (!cleanIt) {
		
			boolean libInstall = false;
			
			// if the lib folder is selected, copy all
			if (requestData.get("PAWSLibsInstall") != null) {
				if ((Integer)requestData.get("PAWSLibsInstall") == 1) {
					
					PAWSInstaller.LOG_FILE.log(Level.ALL,"Mirroring entire lib folder");
					
					libInstall = true;
					
					String destFolder = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawslibfolder");
					
					FileOperations.mirrorDirectories(new File(ConfigManager.getProperty("app.remoteinstall.source.pawslibfolder")),new File(destFolder));
					
					// if PAWS Manager not included, then delete the version just copied from the client
					if (requestData.get("PAWSManagerInstall") != null) {
						if ((Integer)requestData.get("PAWSManagerInstall") == 0) {
							
							PAWSInstaller.LOG_FILE.log(Level.ALL,"Deleting PAWS Client Manager...not required");
							
							// delete the existing PAWS Manager file
							String destFile = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsclientmanager");
							deleteFile(destFile);
						}
					}
				
				}
			}
			
			// else, just copy the pawsclient JAR and PAWS Client Manager jar if required file
			if (!libInstall) {
				
				PAWSInstaller.LOG_FILE.log(Level.ALL,"Copying the PAWS Client JAR");
				
				String destFile = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsclientfile");
				String sourceFile = ConfigManager.getProperty("app.remoteinstall.source.pawsclientfile");
				copyFileToClient(sourceFile,destFile);
				
				if (requestData.get("PAWSManagerInstall") != null) {
					if ((Integer)requestData.get("PAWSManagerInstall") == 1) {
						
						PAWSInstaller.LOG_FILE.log(Level.ALL,"Copying the PAWS Client Manager JAR");
						
						destFile = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsclientmanager");
						sourceFile = ConfigManager.getProperty("app.remoteinstall.source.pawsclientmanager");
						copyFileToClient(sourceFile,destFile);
						
					}
				}
				
			}
				
			// copy the config folder, if selected
			if (requestData.get("PAWSConfigInstall") != null) {
				if ((Integer)requestData.get("PAWSConfigInstall") == 1) {
					
					PAWSInstaller.LOG_FILE.log(Level.ALL,"Mirroring entire config folder");
					
					String destFile = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsconfigfolder");
					
					FileOperations.mirrorDirectories(new File(ConfigManager.getProperty("app.remoteinstall.source.pawsconfigfolder")),new File(destFile));
				}
			}	
		}
			
		// start the PAWS Client service
		togglePAWSService(true,(String)requestData.get("FQDN"));
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_COMPLETED);
		
	}
	
	/**
	 * Perform a full PAWS client installation on the computer
	 */
	private void fullInstall() {
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_INPROGRESS);
		
		// stop the PAWS Client service
		togglePAWSService(false,(String)requestData.get("FQDN"));
		
		// stop windows firewall service
		//toggleFirewallService(false,(String)requestData.get("FQDN"));
		
		boolean cleanIt = false;
		
		if (requestData.get("CleanDestFolder") != null) {
			if ((Integer)requestData.get("CleanDestFolder") == 1) {
				cleanIt = true;
			}
		}
		
		copyPAWSFolderToClient(cleanIt);
		
		// if PAWS Manager not included, then delete the version just copied from the client
		if (requestData.get("PAWSManagerInstall") != null) {
			if ((Integer)requestData.get("PAWSManagerInstall") == 0) {
				
				// delete the exisiting PAWS Manager file
				String destFile = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsclientmanager");
				deleteFile(destFile);
			}
		}
		
		// check if Java install is required
		if (requestData.get("JavaInstall") != null) {
			
			if ((Integer)requestData.get("JavaInstall") == 1) {
				
				if (PAWSInstaller.getPowershellMode()) {
					executeRemotePowershell((String)requestData.get("FQDN"),ConfigManager.getProperty("app.psinstall.java.install"));
				}
				else {
					executeRemoteBatch((String)requestData.get("FQDN"),ConfigManager.getProperty("app.remoteinstall.java.install"),"",true);
				}
			}
		}
		
		// install the PAWS Client service
		if (PAWSInstaller.getPowershellMode()) {
			executeRemotePowershell((String)requestData.get("FQDN"),ConfigManager.getProperty("app.psinstall.pawsclient.install"));
		}
		else {
			executeRemoteBatch((String)requestData.get("FQDN"),ConfigManager.getProperty("app.remoteinstall.pawsclient.install"),"",true);
		}
		
		// wait for the batch file to be completed
		try {
			Thread.currentThread().sleep(10000);
		} 
		catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		// run the configure script on the client
		if (PAWSInstaller.getPowershellMode()) {
			executeRemotePowershell((String)requestData.get("FQDN"),ConfigManager.getProperty("app.psinstall.pawsclient.configure"));
		}
		else {
			executeRemoteBatch((String)requestData.get("FQDN"),ConfigManager.getProperty("app.remoteinstall.pawsclient.configure"),"/NOWAIT",false);
		}
		
		// start the PAWS Client service
		togglePAWSService(true,(String)requestData.get("FQDN"));
		
		// start Windows Firewall service 
		//toggleFirewallService(true,(String)requestData.get("FQDN"));
		
		// check if IdleLogger is required
		if (requestData.get("IdleLoggerInstall") != null) {
			
			if ((Integer)requestData.get("IdleLoggerInstall") == 1) {
				
				if (PAWSInstaller.getPowershellMode()) {
					executeRemotePowershell((String)requestData.get("FQDN"),ConfigManager.getProperty("app.psinstall.idlelogger.install"));
				}
				else {
					executeRemoteBatch((String)requestData.get("FQDN"),ConfigManager.getProperty("app.remoteinstall.idlelogger.install"),"",true);
				}
			}
		}
		
		updateRequestStatus(((Long)requestData.get("ID")).longValue(),Constants.PAWSINSTALL_COMPLETED);
		
	}
	
	/**
	 * Performs a simple file copy
	 * @param sourceFile The path to the source file to be copied
	 * @param destFile The path to the destination file
	 * @return Returns true if file copy has been successful
	 */
	private boolean copyFileToClient(String sourceFile, String destFile) {
		
		try {
			
			// delete original PAWS Manager file
			deleteFile(destFile);
			
			FileOperations.copyFile(new File(sourceFile),new File(destFile));
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return true;
	}
	
	/**
	 * Performs a file deletion on the specified file
	 * @param destFile The path to the file to be deleted
	 * @return Returns true if deletion was successful
	 */
	private boolean deleteFile(String destFile) {
		
		if (new File(destFile).exists()) {
			return new File(destFile).delete();
		}
		
		return true;
	}
	
	/**
	 * Performs a full copy of the PAWS folder to the required destination
	 * @param cleanDestFolder The path to the destination folder in which PAWS will be copied to
	 * @return Returns true if complete copy was successful
	 */
	private boolean copyPAWSFolderToClient(boolean cleanDestFolder) {
		
		// check for existence of source paws client folder.
		String clientFolder = ConfigManager.getProperty("app.remoteinstall.source.pawsclient");
		
		String destFolder = "\\\\"+(String)this.requestData.get("FQDN")+"\\"+ConfigManager.getProperty("app.remoteinstall.dest.pawsclient");
		
		if (cleanDestFolder) {
			PAWSInstaller.LOG_FILE.log(Level.ALL,"Deleting folder: "+destFolder);
			
			FileOperations.deleteDirectory(destFolder);
			
			new File(destFolder).mkdir();
		}
		
		if (new File(clientFolder).exists()) {
			
			if (new File(clientFolder).isDirectory()) {
				
				try {
					
					PAWSInstaller.LOG_FILE.log(Level.ALL,"Mirroring dir from "+clientFolder+" to "+destFolder);
							
					FileOperations.mirrorDirectories(new File(clientFolder),new File(destFolder));		
				}

				catch (Exception ex) {
					ex.printStackTrace();
				}
			
				return true;
			}
		}
		
		return false;

	}
}
